package com.power.sfding.approve.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.exception.BusinessException;
import com.power.flowable.api.IPersonalFeign;
import com.power.flowable.model.pageinfo.BusinessPageInfo;
import com.power.sfding.approve.api.IApl_statisticAppFeign;
import com.power.sifa.approve.model.enumeration.St_apply;
import com.power.sifa.approve.model.enumeration.Tp_proctypeEnum;
import com.power.sifa.approve.service.Apl_mainService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @ClassName Apl_statisticAppController
 * @Author xiongzw
 * @Date 2024/1/31 20:38
 * @Description //赣政通APP首页统计
 * @Version: 1.0
 **/

@Slf4j
@RestController
@Api(value = "Apl_statisticAppController",tags={"赣政通APP首页统计"})
public class Apl_statisticAppController implements IApl_statisticAppFeign {

    @Resource
    private IPersonalFeign iPersonalFeign;
    @Resource
    private Apl_mainService apl_mainService;

    /**
     * 线程池
     */
    public ExecutorService threadPool = new ThreadPoolExecutor(8, 16, 2, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());

    @Override
    public ResponseDTO queryCaseStatistics(String userid) throws BusinessException {
        // 异步线程数
        CountDownLatch latch = new CountDownLatch(3);

        BusinessPageInfo pageInfo = new BusinessPageInfo();
        // 设置当前的查询状态
        pageInfo.setPageSize(99999);
        // 默认流程中的状态
        pageInfo.setState(1);

        Map<String, Object> result = new HashMap<>(16);
        // 1. 我的待办总数
        {
            Runnable runner = () -> {
                Thread.currentThread().setName("thread-pool-taskList");
                ResponseDTO res = this.iPersonalFeign.taskList(userid, pageInfo);
                // 查询当前补正的数据
                // 数据初始化
                result.put("todoTotal", 0);
                result.put("appendTotal", 0);
                result.put("mediateTotal", 0);

                if (ObjectUtil.isNotNull(res) && res.getCode() == 0) {
                    // 查询当前的待处理的数据
                    Integer total = (Integer) ((Map) res.getData()).get("total");
                    result.put("todoTotal", total);
                    List<Map> resultList = JSON.parseArray(JSON.toJSONString(((Map) res.getData()).get("records")), Map.class);
                    if (CollectionUtil.isEmpty(resultList)) {
                        // 补正数据
                        result.put("appendTotal", resultList.stream().filter(el -> ObjectUtil.isNotNull(el) && el.get(
                                "processkey").equals(Tp_proctypeEnum.ACCEPT_APPEND.getProcesskey())).count());
                        // 调解数据
                        result.put("mediateTotal", resultList.stream().filter(el -> ObjectUtil.isNotNull(el) && el.get(
                                "processkey").equals(Tp_proctypeEnum.MATER_MEDIATE.getProcesskey())).count());
                    }
                }
                latch.countDown();
            };
            threadPool.execute(runner);
        }

        // 2. 我的已办总数
        {
            Runnable runner = () -> {
                Thread.currentThread().setName("thread-pool-endBusinessList");
                Integer total = this.apl_mainService.countByUserAndStatus(userid, St_apply.COMPLETELIST);
                if(null != total) {
                    result.put("compleTotal", total);
                } else {
                    result.put("compleTotal", total);
                }
                latch.countDown();
            };
            threadPool.execute(runner);
        }

        // 3. 全局已办总数
        {
            Runnable runner = () -> {
                Thread.currentThread().setName("thread-pool-countByStatus");
                Integer total = this.apl_mainService.countByStatus(St_apply.COMPLETELIST);
                if(null != total) {
                    result.put("allTotal", total);
                } else {
                    result.put("allTotal", total);
                }
                latch.countDown();
            };
            threadPool.execute(runner);
        }


        try {
            // 等待子线程结束
            latch.await();
            Thread.sleep(500);
        } catch (InterruptedException e) {
            log.error("/statistic/queryCaseStatistics 线程 latch await" + e.getMessage());
            Thread.currentThread().interrupt();
        }
        return ResponseDTO.succData(result);
    }
}
